package com.maxmlr.music.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * 摘要加密工具
 */
public class Md5Util {

	/**
	 * 对传入的字符串进行摘要加密， 返回加密后的密文。 Md5Util.md5("qqq");
	 */

	public static String md5(String data) {
		try {
			byte[] md = data.getBytes("utf-8");
//			System.out.println("md5 :" + Arrays.toString(md));
			byte[] md5 = md5(md);
			return toHexString(md5);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static byte[] md5(byte[] data) {
		try {
			MessageDigest md = MessageDigest.getInstance("md5");
			md.update(data);
			byte[] buf = md.digest();
//			System.out.println("md5_byte[] :" + Arrays.toString(buf));
			return buf;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return new byte[] {};

	}

	public static String toHexString(byte[] md5) {
		StringBuilder buf = new StringBuilder();
		for (byte b : md5) {
			buf.append(leftPad(Integer.toHexString(b & 0xff), '0', 2));
		}
		String str = buf.toString();
		return str;
	}

	public static String leftPad(String hex, char c, int size) {
//		System.out.println("leftPad :" + hex);
		char[] cs = new char[size];
		Arrays.fill(cs, c);
		System.arraycopy(hex.toCharArray(), 0, cs, cs.length - hex.length(),
				hex.length());
		String css = new String(cs);
//		System.out.println("css " + css);
		return css;
	}

	public static void main(String[] args) {
		
		System.out.println(md5("123123"));
	}// 202cb962ac59075b964b07152d234b70
	// 202cb962ac59075b964b07152d234b70
} // a0a080f42e6f13b3a2df133f073095dd
